package nix.anim.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import nix.anim.common.pojo.NixResult;
import nix.anim.common.pojo.TreeNode;
import nix.anim.mapper.MenuMapper;
import nix.anim.pojo.Menu;
import nix.anim.pojo.MenuExample;
import nix.anim.pojo.MenuExample.Criteria;
import nix.anim.service.MenuService;

/**
 * 菜单管理Service
 */
@Service
public class MenuServiceImpl implements MenuService {

	@Autowired
	private MenuMapper menuMapper;
	
	@Override
	public NixResult addMenu(Menu menu) {
		// 补全属性
		menu.setIsParent(false);
		// 状态：1、正常；2、禁用；
		menu.setStatus(1);
		// 插入数据库
		menuMapper.insert(menu);
		// 判断父节点状态
		Menu parent = menuMapper.selectByPrimaryKey(menu.getParentId());
		if (parent != null && !parent.getIsParent()) {
			// 更新为父节点
			parent.setIsParent(true);
			menuMapper.updateByPrimaryKeySelective(parent);
		}
		// 返回结果
		return NixResult.ok();
	}

	@Override
	public NixResult deleteAll() {
		// 删除所有
		menuMapper.deleteByExample(new MenuExample());
		return NixResult.ok();
	}

	@Override
	public NixResult getMenuTree(Integer parentId) {
		// 调用递归方法，获得List<TreeNode>
		List<TreeNode> list = getMenuNodesByParentId(parentId);
		return NixResult.ok(list);
	}
	
	private List<TreeNode> getMenuNodesByParentId(Integer parentId) {
		List<TreeNode> list = new ArrayList<>();
		// 查询条件：parentId
		MenuExample menuExample = new MenuExample();
		Criteria criteria = menuExample.createCriteria();
		criteria.andParentIdEqualTo(parentId);
		criteria.andStatusEqualTo(1);
		List<Menu> menuList = new ArrayList<>();
		menuList = menuMapper.selectByExample(menuExample);	
		// 判断，遍历，组装TreeNode
		if (menuList != null && menuList.size() >= 0) {
			for (Menu menu : menuList) {
				TreeNode node = new TreeNode();
				node.setId(menu.getId());
				node.setName(menu.getName());
				node.setData(menu);
				// 判断：是父节点，则递归子节点
				if (menu.getIsParent()) {
					node.setChildren(getMenuNodesByParentId(menu.getId()));
				}
				list.add(node);
			}
		}
		return list;
	}

}
